package com.mofum.msdom.excel.template.hander.poi;

import com.mofum.msdom.excel.constant.TemplateConfig;
import com.mofum.msdom.excel.template.event.TemplateCallback;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.usermodel.XSSFComment;

import java.util.List;

/**
 * @author yuyang@qxy37.com
 * @since 2019/2/1 0001 16:33
 */
public class TemplateCellReadHandler implements XSSFSheetXMLHandler.SheetContentsHandler {

    /**
     * 模板配置
     */
    private TemplateConfig templateConfig;

    /**
     * 属性读取回调
     */
    private TemplateCallback templatePropCallback;

    /**
     * 值读取回调
     */
    private TemplateCallback valuePropCallback;

    @Override
    public void startRow(int i) {

    }

    @Override
    public void endRow(int i) {

    }

    @Override
    public void cell(String cellReference, String formattedValue, XSSFComment comment) {
        CellReference reference = new CellReference(cellReference);
        int colIndex = reference.getCol();
        int rowIndex = reference.getRow();

        String outValue = formattedValue;

        //表达式处理
        boolean hasExpression = TemplateConfig.isHasItemRegExpressions(templateConfig.getItemReg(), formattedValue);

        if (hasExpression) {
            List<String> codes = TemplateConfig.getMatcher(templateConfig.getItemReg(), formattedValue);

            outValue = TemplateConfig.replaceReg(templateConfig.getExtractReg(), outValue);

            for (String code : codes) {

                String propName = TemplateConfig.replaceName(templateConfig.getExtractReg(), code);

                String value = getTemplatePropCallback().call(propName, rowIndex, colIndex);

                outValue = TemplateConfig.replaceSingleProp(propName, outValue, value);

            }

        }

        valuePropCallback.call(outValue, rowIndex, colIndex);

    }


    public TemplateConfig getTemplateConfig() {
        if (templateConfig == null) {
            templateConfig = TemplateConfig.DEFAULT_CONFIG;
        }

        return templateConfig;
    }

    public void setTemplateConfig(TemplateConfig templateConfig) {
        this.templateConfig = templateConfig;
    }

    public TemplateCallback getTemplatePropCallback() {
        if (templatePropCallback == null) {
            templatePropCallback = TemplateCallback.DEFAULT;
        }

        return templatePropCallback;
    }

    public void setTemplatePropCallback(TemplateCallback templatePropCallback) {
        this.templatePropCallback = templatePropCallback;
    }

    public TemplateCallback getValuePropCallback() {
        if (templatePropCallback == null) {
            templatePropCallback = TemplateCallback.DEFAULT;
        }

        return valuePropCallback;
    }

    public void setValuePropCallback(TemplateCallback valuePropCallback) {
        this.valuePropCallback = valuePropCallback;
    }
}
